package org.jeecg.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.entity.*;
import org.jeecg.common.service.FloorService;
import org.jeecg.common.service.IDXFDataService;
import org.jeecg.common.service.IHsPersonService;
import org.jeecg.common.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "erp示例")
@RestController
@RequestMapping("/dxf")
@Slf4j
public class ErpHelloController {

	@Autowired
	private IDXFDataService dxfDataService;
	@Autowired
	private RoomService roomService;
	@Autowired
	private FloorService floorService;
	@Autowired
	private IHsPersonService hsPersonService;

	@ApiOperation(value = "hello", notes = "对外服务接口")
	@GetMapping(value = "/erpDoGet2")
	public Result<?> sayHello() {
		log.info(" ---我被调用了--- ");
		return Result.OK("/erpDoGet2");
	}
//	@GetMapping(value = "/list")
//	public Result<List<DXFData>> getList() {
//		return Result.OK(dxfDataService.list());
//	}
//	@PostMapping(value = "/save")
//	public Result<Void>  save(@RequestBody DXFData dxfData) {
//		dxfDataService.saveOrUpdate(dxfData);
//		return Result.OK();
//	}
//	@DeleteMapping(value = "/delete/{ids}")
//	public Result<Void> delete(@NotEmpty(message = "主键不能为空")
//						   @PathVariable Long[] ids) {
//		dxfDataService.removeByIds(Arrays.asList(ids));
//		return Result.OK();
//	}
	@GetMapping(value = "/floor/list")
	public Result<List<Floor>> getFloorList() {
		return Result.OK(floorService.list());
	}
	@PostMapping(value = "/floor/setting")
	public Result<Void>  saveFloor(@RequestBody Floor floor) {
		floorService.updateById(floor);
		return Result.OK();
	}

	@GetMapping(value = "/room/list/{floorId}")
	public Result<List<Room>> getRoomListByFloorId(@PathVariable String floorId) {
		return Result.OK(roomService.queryListWithUsedAreaByFloorId(floorId));
	}

	@PostMapping(value = "/saveRoom")
	public Result<Void>  saveRoom(@RequestBody Room room) {
		roomService.saveOrUpdate(room);
		return Result.OK();
	}
	@PostMapping(value = "/saveRoomBatch/{floorId}")
	public Result<Void>  saveRoomBatch(@RequestBody List<Room> roomList,@PathVariable String floorId) {
		//检验是否存在该楼层
		Floor floor = floorService.getById(floorId);
		if(floor==null){
			return Result.error("楼层不存在");
		}
		//删除原有房间
		roomService.remove(new LambdaQueryWrapper<Room>().eq(Room::getBasicsFloorId, floorId));
		for (Room room : roomList) {
			room.setBasicsFloorId(floorId);
		}
		roomService.saveOrUpdateBatch(roomList);
		return Result.OK();
	}
	@DeleteMapping(value = "/room/delete/{ids}")
	public Result<Void> deleteRoom(@NotEmpty(message = "主键不能为空")
						   @PathVariable Long[] ids) {
		roomService.removeByIds(Arrays.asList(ids));
		return Result.OK();
	}
	@PostMapping(value = "/room/deal")
	public Result<Void> dealRooms(@RequestBody RoomDeal deal) {
		Floor floor = floorService.getById(deal.getFloorId());
		if(floor==null){
			return Result.error("楼层不存在");
		}
		roomService.removeByIds(deal.getDeleteRoomIds());
		List<Room> saveRooms = deal.getSaveRooms();
		for (Room room : saveRooms) {
			room.setBasicsFloorId(deal.getFloorId());
		}
		roomService.saveOrUpdateBatch(saveRooms);
		return Result.OK();
	}

	@GetMapping(value = "/people/list")
	public Result<Page<HsPerson>> getPersonList(@RequestParam(name = "name", required = false) String name, @RequestParam(name = "pageNo", required = false) Integer pageNo, @RequestParam(name = "pageSize", required = false) int pageSize) {
		return Result.OK(hsPersonService.queryPage(name, new Page<>(pageNo, pageSize)));
	}
	@GetMapping(value = "/room/people/{roomId}")
	public Result<List<HsPerson>> getRoomPeople(@PathVariable(name = "roomId") String roomId) {
		LambdaQueryWrapper<HsPerson> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(HsPerson::getBaseinfoRoomId, roomId);
		return Result.OK(hsPersonService.list(queryWrapper));
	}
	@PostMapping(value = "/room/people")
	public Result<Void> saveRoomPeople(@RequestBody AssignPeople assign) {
		Room room = roomService.getById(assign.getRoomId());
		if(room==null){
			return Result.error("房间不存在");
		}
		LambdaQueryWrapper<HsPerson> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(HsPerson::getBaseinfoRoomId, assign.getRoomId());
		List<HsPerson> oldPeopleList = hsPersonService.list(queryWrapper);
		List<String> newPeopleIds = assign.getPeopleIds();
		List<HsPerson> upDateList = new ArrayList<>();

		// 处理新增或更新的人员：设置他们的房间ID为当前房间ID
		if (newPeopleIds != null && !newPeopleIds.isEmpty()) {
			LambdaQueryWrapper<HsPerson> personQuery = new LambdaQueryWrapper<>();
			personQuery.in(HsPerson::getId, newPeopleIds);
			List<HsPerson> newPeopleList = hsPersonService.list(personQuery);

			for (HsPerson person : newPeopleList) {
				person.setBaseinfoRoomId(assign.getRoomId());
				upDateList.add(person);
			}
		}

		// 获取旧人员ID列表
		List<String> oldPeopleIds = oldPeopleList.stream()
				.map(HsPerson::getId)
				.collect(Collectors.toList());

		// 找出需要移除房间关联的人员（在旧列表中但不在新列表中的人员）
		List<String> toRemoveIds = oldPeopleIds.stream()
				.filter(id -> newPeopleIds == null || !newPeopleIds.contains(id))
				.collect(Collectors.toList());

		// 将需要移除房间关联的人员加入更新列表
		if (!toRemoveIds.isEmpty()) {
			List<HsPerson> removeList = toRemoveIds.stream()
					.map(id -> {
						HsPerson p = new HsPerson();
						p.setId(id);
						p.setBaseinfoRoomId(null); // 移除房间关联
						return p;
					})
					.collect(Collectors.toList());
			upDateList.addAll(removeList);
		}

		// 一次性批量更新所有人员信息
		if (!upDateList.isEmpty()) {
			hsPersonService.updateBatchById(upDateList);
		}
		return Result.OK();
	}
}
